import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Observable } from 'rxjs';

// https://stackoverflow.com/a/62046792/9672709
// export const AppGuard = (from: string) => {
//   @Injectable()
//   class AppGuardMixed implements CanActivate {
//     constructor(private readonly reflect: Reflector) {}
//     canActivate(
//       context: ExecutionContext,
//     ): boolean | Promise<boolean> | Observable<boolean> {
//       const req = context.switchToHttp().getResponse();
//       const rolesMethods = this.reflect.get<string[]>(
//         'roles',
//         context.getHandler(),
//       );
//       const testMethods = this.reflect.get<any>('test', context.getHandler());
//       console.group(`appGuard at ${from}`);
//       console.log('rolesMethods', rolesMethods);
//       console.log('testMethods', testMethods);
//       console.groupEnd();
//       return true;
//     }
//   }
//   return mixin(AppGuardMixed);
// };

@Injectable()
export class AppGuard implements CanActivate {
  constructor(private reflect: Reflector) {}
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const rolesContorller = this.reflect.get<string[]>(
      'admin-controller',
      context.getClass(),
    );
    const testController = this.reflect.get<string[]>(
      'test-controller',
      context.getClass(),
    );
    const rolesMethods = this.reflect.get<string[]>(
      'roles',
      context.getHandler(),
    );
    const testMethods = this.reflect.get<any>('test', context.getHandler());
    console.group(`appGuard in`);
    console.log('rolesController', rolesContorller);
    console.log('rolesMethods', rolesMethods);
    console.log('testController', testController);
    console.log('testMethods', testMethods);
    console.groupEnd();
    return true;
  }
}
